package yl.hs.bmipfull.service.salemanage.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import yl.hs.bmipfull.daos.salemanage.IBuildProjectInfoDao;
import yl.hs.bmipfull.daos.salemanage.ILinkerInfoDao;
import yl.hs.bmipfull.pojo.production.ProductionLinePortEntity;
import yl.hs.bmipfull.pojo.production.ProductionTaskEntity;
import yl.hs.bmipfull.pojo.salemanage.BuildProjectInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.LinkerInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleContractEntity;
import yl.hs.bmipfull.service.salemanage.IBuildProjectInfoService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.util.List;
import java.util.Map;

/**
 * 作用:  客户工地信息服务层接口实现<br/>
 * 创建时间: 2021年05月19日 14时41分05秒 <br/>
 *
 * @author 谢东
 */
@Service
public class BuildProjectInfoServiceImpl extends SaleBaseService implements IBuildProjectInfoService {

    @Autowired
    IBuildProjectInfoDao dao;
    @Autowired
    ILinkerInfoDao linkerDao;

    @Override
    public List<BuildProjectInfoEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(BuildProjectInfoEntity.class);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),BuildProjectInfoEntity.class);
        return dao.queryList(pageQuery.getQuery(), getTagSNs());
    }

    @Override
    public PageResult<BuildProjectInfoEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(BuildProjectInfoEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<BuildProjectInfoEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),BuildProjectInfoEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(), getTagSNs(), filters));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery(), getTagSNs(),filters));
        return result;
    }


    @Override
    public BuildProjectInfoEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer saveBuildProjectInfo(Map<String, Object> model, String sn) throws Exception {
        Integer result;
        try {
            if (Tl.isEmpty(sn)) {
                //执行保存
                BuildProjectInfoEntity entity = new BuildProjectInfoEntity();
                Tl.getChangeLog(entity, model);
                entity.setPYFieldValue();
                result = createProject(entity);
                if(result>0){
                    createLinkerInfo(entity);
                    //createProject(entity);
                }
            } else {
                //执行修改
                var entity = findBySn(sn);
                var backJson = entity.toJson();
                var changeLog =
                        Tl.getChangeLog(entity, model);
                entity.setPYFieldValue();
                result = dao.update(entity);
                if (result > 0) {
                    createLinkerInfo(entity);
                    writeLog(ActionType.UPDATE, sn, changeLog, backJson, BuildProjectInfoEntity.class);
                    saveGS(
                            entity.getSn(),
                            entity.getProjectName(),
                            String.join(",",
                                    entity.getProjectName(),
                                    entity.getAddress(),
                                    entity.getArea(),
                                    entity.getCustomerName(),
                                    entity.getOwnerName(),
                                    entity.getSupervision(),
                                    entity.getBuildName()
                            ),
                            entity,
                            HsApp.getCurrent().getUserSN(),
                            null
                    );
                }
            }
        } catch (Exception ee) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw ee;
        }
        return result;
    }

    private Integer createLinkerInfo(BuildProjectInfoEntity projectEntity) {
        LinkerInfoEntity linkEntity = new LinkerInfoEntity();
            Integer isHave = linkerDao.findLinkerCountByCustSnAndFullName(projectEntity.getSn(), projectEntity.getLinkerName());
            if (isHave > 0) {
                linkEntity.setCustSn(projectEntity.getSn());
                linkEntity.setCustType((short) 2);
                linkEntity.setFullName(projectEntity.getLinkerName());
                Integer result = linkerDao.insertNew(linkEntity);
                if (result > 0) {
                    writeLog(ActionType.CREATE, linkEntity.getSn(), "插入联系人表信息", Tl.toJson(linkEntity), LinkerInfoEntity.class);
                }
                return result;
            }

        return 0;
    }
    @Override
    public String saveBuildProjectInfo(String projectName, String address) throws Exception {
        BuildProjectInfoEntity projectEntity = new BuildProjectInfoEntity();
        projectEntity.setProjectName(projectName);
        projectEntity.setAddress(address);
        createProject(projectEntity);
        return projectEntity.getSn();
    }

    @Override
    @Transactional
    public Integer delete(String[] sn) {
        var result = dao.changeStateBySn(sn, DataState.DELETED.code);
        if (result > 0) {
            writeLog(ActionType.DELETE, sn, BuildProjectInfoEntity.class);
            deleteGs(sn);
        }
        return result;
    }

    @Override
    public BuildProjectInfoEntity findByName(String projectName) {
        return dao.findByName(projectName);
    }

    @Override
    public Integer createProject(BuildProjectInfoEntity entity) throws Exception {
        entity.setPYFieldValue();
        entity.setSn(queryNewSN(BuildProjectInfoEntity.class));
        entity.setOrganizationCode(getDepartSN());
        var result = dao.insertNew(entity);
        if (result > 0) {
            var shareCode = writeUserTag(entity.getSn(), entity.getClass(), RelationType.CREATE.toString());
            writeLog(ActionType.CREATE, entity.getSn(), "插入客户工地信息信息", Tl.toJson(entity), BuildProjectInfoEntity.class);

            saveGS(
                    entity.getSn(),
                    entity.getProjectName(),
                    String.join(",",
                            entity.getProjectName(),
                            entity.getAddress(),
                            entity.getArea(),
                            entity.getCustomerName(),
                            entity.getOwnerName(),
                            entity.getSupervision(),
                            entity.getBuildName()
                    ),
                    entity,
                    shareCode,
                    HsApp.getCurrent().getUserSN()
            );
        }
        return result;
    }

    @Override
    public Integer changeStateBySn(String[] snArray, short state) {
        int result=dao.changeStateBySn(snArray,state);
        if (result > 0) {
            forWriteLog(snArray,state);
        }
        return result;
    }
}